

package com.maoshi.shop.discount.platform.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.bean.enums.OfflineHandleEventType;
import com.maoshi.shop.bean.model.OfflineHandleEvent;
import com.maoshi.shop.bean.model.Product;
import com.maoshi.shop.bean.param.OfflineHandleEventAuditParam;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.discount.comment.model.Discount;
import com.maoshi.shop.discount.comment.model.DiscountProd;
import com.maoshi.shop.discount.comment.service.DiscountService;
import com.maoshi.shop.security.multishop.util.SecurityUtils;
import com.maoshi.shop.service.OfflineHandleEventService;
import com.maoshi.shop.service.ProductService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;


/**
 * @author lgh on 2018/11/21.
 */
@RestController
@RequestMapping("/admin/discount")
@AllArgsConstructor
public class DiscountController {

    private DiscountService discountService;
    private ProductService productService;
    private OfflineHandleEventService offlineHandleEventService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<Discount>> page(Discount discount, PageParam<Discount> page) {
        IPage<Discount> discounts = discountService.page(page,
                new LambdaQueryWrapper<Discount>()
                        .eq(Objects.nonNull(discount.getStatus()), Discount::getStatus, discount.getStatus())
                        .like(StringUtils.isNotBlank(discount.getDiscountName()), Discount::getDiscountName, discount.getDiscountName())
                        .eq(Discount::getShopId, SecurityUtils.getShopUser().getShopId()));
        return ResponseEntity.ok(discounts);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{discountId}")
    public ResponseEntity<Discount> info(@PathVariable("discountId") Long discountId) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Discount discount = discountService.getDiscountAndItemAndProdById(discountId);
        if (!Objects.equals(shopId, discount.getShopId())) {
            throw new MaoshiShopBindException("您无权获取此活动信息");
        }
        return ResponseEntity.ok(discount);
    }

    /**
     * 保存
     */
    @PostMapping
    public ResponseEntity<String> save(@RequestBody @Valid Discount discount) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        discount.setShopId(shopId);
        List<DiscountProd> discountProds = discount.getDiscountProds();
        StringBuilder missProdNames = new StringBuilder();
        if (CollectionUtil.isNotEmpty(discountProds)) {
            for (DiscountProd discountProd : discountProds) {
                Product product = productService.getProductByProdId(discountProd.getProdId());
                if (product == null) {
                    missProdNames.append(discountProd.getProdName()).append(" ");
                }
            }
        }
        if (missProdNames.length() > 0) {
            return ResponseEntity.badRequest().body("活动中包含已下线商品：[ " + missProdNames.toString() + "]");
        }

        discountService.insertDiscountAndItemAndProd(discount);


        return ResponseEntity.ok().build();
    }

    /**
     * 修改
     */
    @PutMapping
    public ResponseEntity<Void> update(@RequestBody @Valid Discount discount) {
        discountService.updateDiscountAndItemAndProd(discount);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{discountId}")
    public ResponseEntity<Void> delete(@PathVariable Long discountId) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        discountService.deleteDiscountsAndItemsAndProds(discountId, shopId);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过活动id获取下线信息
     */
    @GetMapping("/getOfflineHandleEventByDiscountId/{discountId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventByDiscountId(@PathVariable("discountId") Long discountId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.DISCOUNT.getValue(), discountId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 违规商品提交审核
     */
    @PostMapping("/auditApply")
    public ResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Discount discount = discountService.getDiscountAndItemAndProdById(offlineHandleEventAuditParam.getHandleId());
        if (discount == null) {
            throw new MaoshiShopBindException("未找到此活动信息");
        }
        // 提交审核
        discountService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        // 移除缓存
        discountService.removeDiscountsAndItemsCacheByShopId(discount.getShopId());
        discountService.removeDiscountAndItemAndProdCacheById(discount.getDiscountId());
        return ResponseEntity.ok().build();
    }
}
